﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Net;
using System.Net.Mail;
using Nivdal.AuxCode;

namespace Nivdal
{
     

    public partial class Register : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string version = "";
            try { version = ConfigurationManager.AppSettings["version"]; }
            catch { version = "999.0.0.0"; }

            NoamStylesGlobalLiteral.Text = "<link href=\"NoamStyles/Global.css?v=" + version + "\" rel=\"stylesheet\" type=\"text/css\" />";
            NoamStylesDefaultLiteral.Text = "<link href=\"NoamStyles/Default.css?v=" + version + "\" rel=\"stylesheet\" type=\"text/css\" />";
            StylesheetNewLiteral.Text = "<link href=\"StyleSheetNew.css?v=" + version + "\" rel=\"stylesheet\" type=\"text/css\" />";
            RegisterCssLiteral.Text = "<link href=\"Register.css?v=" + version + "\" rel=\"stylesheet\" type=\"text/css\" />";

            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.Register_PageTitle;
            if (!IsPostBack)
            {
                if (Request.QueryString["RegisterId"] != null)
                    this.RegisterIdHiddenField.Value = Request.QueryString["RegisterId"].ToString();

            }

            if (!IsPostBack)
            {
                DateTime ServerTime = System.DateTime.Now;

                OnlineUser ou = (OnlineUser)Session["User"];
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

                if (ou.UserId != null)
                {
                    if (!HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        ou.UserId = null;
                        ou.ApprovalStatus = "0";
                        ou.TeamId = null;
                        ou.UserAccessLevel = "0";
                        ou.UserName = null;
                        ou.IsPremium = false;
                    }
                    else
                        Response.Redirect("~/RegistrationMessage.aspx");
                }
                else if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    // if authenticated- logout and reload the page
                    FormsAuthentication.SignOut();
                    Response.Redirect("~/Register.aspx");
                }

                if (HttpContext.Current != null)
                {
                    string current_url = HttpContext.Current.Request.Url.ToString();
                    // Debug.WriteLine("current page " + current_url);
                    string prev_url = Request.ServerVariables["HTTP_REFERER"];
                    //Debug.WriteLine("prev page " + prev_url);
                    GND.ExecNivdalSQL("PageName", "Entry", "NewbieTipStage", "UserId", "Nivdal_AddPageStatistic", prev_url, false, Session["NewbieTipStage"], ou.UserId); 
                    GND.ExecNivdalSQL("PageName", "Entry", "NewbieTipStage", "UserId", "Nivdal_AddPageStatistic", current_url, true, Session["NewbieTipStage"], ou.UserId);                    
                }
            }
            //this.Title = Resources.Resource.Register_Title + " - " + GND.ReturnAppTitle();

            CultureInfo Cult = ResolveCulture();
            if (Cult.TextInfo.IsRightToLeft)
            {
                (LoginView1.FindControl("LoginPanel") as Panel).Direction = ContentDirection.RightToLeft;
                FacebookPanel.Direction = ContentDirection.RightToLeft;
                RegisterWizardPanel.Direction = ContentDirection.RightToLeft;
                DirStylesheetLiteral.Text = "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheetRTL.css\" />";
                //(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Passwordstrength1") as AjaxControlToolkit.PasswordStrength).DisplayPosition = AjaxControlToolkit.DisplayPosition.LeftSide;
            }
            else
            {
                DirStylesheetLiteral.Text = "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheetLTR.css\" />";
            }
            //this.NumberOfOnlineUsersLabel.Text = Application["ActiveUsers"].ToString();
            //this.NumberOfActiveUsersLabel.Text = NumOfActiveUsers().ToString();
            ErrorLabelPanel.Visible = (ErrorLabel.Text.Length > 0);

            string IPAddress = GetIP();
            IPAddressHiddenField.Value = IPAddress;
            decimal IPCountry = GetNivdalData.GetNivdalData.GetIPCountry(IPAddress);
            CountryByIPHiddenField.Value = IPCountry.ToString(); 

            if ((IPCountry > 0) && (!IsPostBack))
            {
                try
                {
                    (CreateUserWizardStep1.ContentTemplateContainer.FindControl("NationalityDropDownList") as DropDownList).SelectedValue = IPCountry.ToString();
                }
                catch { }
            }

            
        }


        /// <summary>
        /// Static method that retrieves the time from the server
        /// </summary>
        /// <returns></returns>
        [System.Web.Services.WebMethod]
        public static bool IsUserAvailable(string username)
        {
            //MembershipUser usr = Membership.GetUser(username);
            //return (usr == null);
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            return GND.ReadNivdalBoolData("UserName", "Nivdal_IsUserNameFree", username);
        }

        [System.Web.Services.WebMethod]
        public static bool CheckEmail(string email)
        {
            try
            {
                string usr = Membership.GetUserNameByEmail(email);
                return (usr == null);
            }
            catch
            {
                return false;
            }

        }

        [System.Web.Services.WebMethod]
        public static bool CheckPublicName (string PublicName)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            try
            {
                return (!GND.ReadNivdalBoolData("@Name", "Nivdal_DoesPublicNameExist", PublicName));

            }
            catch
            {
                return false;
            }

        }


        [System.Web.Services.WebMethod]
        public static bool CheckTeamName(string teamname)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            try
            {
                return (!GND.ReadNivdalBoolData("@Name", "Nivdal_DoesTeamNameExist", teamname));

            }
            catch
            {
                return false;
            }

        }



        protected int NumOfActiveUsers()
        {

            string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlConnection
            strConnection = new System.Data.SqlClient.SqlConnection(conn);
            string StrSQL = "Nivdal_GetNumberOfActiveUsers";
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(StrSQL, strConnection);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ROWCOUNT", System.Data.SqlDbType.Int, 0));
            cmd.Parameters["@ROWCOUNT"].Direction = ParameterDirection.ReturnValue;

            strConnection.Open();
            try
            {

                cmd.ExecuteNonQuery();
                return (int)(cmd.Parameters["@ROWCOUNT"].Value);

            }
            catch (Exception SQLDBException)
            {
                Response.Write(SQLDBException.Message);
                //Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "<script type=\"text/javascript\">alert('" + SQLDBException.Message + "');</script>");
                return 0;

            }

            finally
            {

                strConnection.Close();
            }

        }

        protected AjaxControlToolkit.DisplayPosition GetDisplayPosition()
        {
            AjaxControlToolkit.DisplayPosition Position;
            CultureInfo Cult = ResolveCulture();
            if (Cult.TextInfo.IsRightToLeft)
                Position = AjaxControlToolkit.DisplayPosition.BelowRight;
            else
                Position = AjaxControlToolkit.DisplayPosition.BelowLeft;

            return Position;
        }
       



        protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
        {
            if (RegNoBot.IsValid())
            {
                TextBox UserNameTextBox = (TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("UserName");
                SqlDataSource DataSource = (SqlDataSource)CreateUserWizardStep1.ContentTemplateContainer.FindControl("InsertExtraInfo");

                MembershipUser User = Membership.GetUser(UserNameTextBox.Text);
                object UserGUID = User.ProviderUserKey;

                DataSource.InsertParameters.Add("UserId", UserGUID.ToString());
                DataSource.InsertParameters.Add("RegisterId", RegisterIdHiddenField.Value.ToString());


                DataSource.Insert();
                SendConfMail(UserGUID.ToString());

                // checking whether it is OK to approve the user immediately
                try
                {
                    string IPAddress = IPAddressHiddenField.Value;
                    if (IPAddress.Length > 1)
                    {
                        DropDownList CoutnriesDDL = (DropDownList)CreateUserWizardStep1.ContentTemplateContainer.FindControl("NationalityDropDownList");
                        string SelectedCountry = CoutnriesDDL.SelectedValue;
                        string IPCountry = CountryByIPHiddenField.Value;

                        GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                        if (CheckIPCountry(SelectedCountry, IPCountry) && (!HasIPConflicts(IPAddress, UserGUID.ToString())))
                        {
                            // the user is from a correct country, and has no IP conflicts - thus we can approve him.                            
                            string Answer = GND.ReadNivdalStringData("UserId", "ApproveName", "Nivdal_UserApprovalApproveUser", UserGUID.ToString(), "0");
                            GND.SendPendingMails();
                        }
                        else
                        { 
                            // move user to Admin:
                            string Answer = GND.ReadNivdalStringData("UserId", "Nivdal_UserApprovalMoveToAdmin", UserGUID.ToString());
                        }

                    }
                }
                catch { }
            }
           
        }

        private bool CheckIPCountry(string Country, string IPCountry)
        {
            bool equal = (Country == IPCountry);

            if (!equal)
            {
                // Exception for GB countries
                if ((Country == "12" || Country == "76" || Country == "77" || Country == "78") &&
                    (IPCountry == "12" || IPCountry == "76" || IPCountry == "77" || IPCountry == "78"))
                {
                    equal = true;
                }
            }
            return equal;
        }


        private bool HasIPConflicts(string IPAddress, string UserId)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            return GND.ReadNivdalBoolData("IPAddress", "UserId", "Nivdal_DoesUserHaveIPConflict", IPAddress, UserId);
        }

       

        protected void SendConfMail(string UserId)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string ConformationCode = GND.ReadNivdalStringData("UserId", "Nivdal_GetUserMailConformationCode", UserId);
            String MailSender = "admin@nivdal.com";
            MailAddress SendFrom = new MailAddress(MailSender);
            MailAddress SendTo = new MailAddress(CreateUserWizard1.Email.ToString());
            System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage(SendFrom, SendTo);
            m.BodyEncoding = System.Text.Encoding.UTF8;
            m.Subject = Resources.Resource.Registration_Subject;
            m.Body = " ";
            m.Body += Environment.NewLine + Resources.Resource.Registration_ThankYou;
            m.Body += Environment.NewLine + Resources.Resource.Registration_UserName + " " + CreateUserWizard1.UserName.ToString();
            m.Body += Environment.NewLine + Resources.Resource.Registration_Password + " " + CreateUserWizard1.Password.ToString();
            m.Body += Environment.NewLine + Resources.Resource.Registration_Confirm;
            m.Body += Environment.NewLine +  " http://www.nivdal.com/ApproveEmail.aspx?Code=" + ConformationCode;

            m.Body += Environment.NewLine + Resources.Resource.Registration_regards;
            m.BodyEncoding = System.Text.Encoding.UTF8;
            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); 
 
            // gmail only section
            //smtp.Host = "smtp.gmail.com";
            //smtp.Port = 25;
            //smtp.Port = 587;
            //smtp.EnableSsl = true;
            //smtp.UseDefaultCredentials = false;
            //smtp.Credentials = new NetworkCredential("nivdal@gmail.com", "pasha2@2");
            try
            {
                smtp.Send(m);
                ErrorLabel.Text = "mail was sent!";
            }
            catch (Exception ex) { ErrorLabel.Text = (ex.Message); }

        }


        public static CultureInfo ResolveCulture()
        {
            string[] languages = HttpContext.Current.Request.UserLanguages;
            if (languages == null || languages.Length == 0)
                return null;
            try
            {
                string language = languages[0].ToLowerInvariant().Trim();
                return System.Globalization.CultureInfo.CreateSpecificCulture(language);
            }
            catch (ArgumentException)
            {
                return null;
            }
        }


        protected String UserEmail()
        {

            return CreateUserWizard1.Email.ToString();
        }
        
        public string GetIP()
        {
            try
            {
                HttpRequest currentRequest = HttpContext.Current.Request;
                string ipAddress = currentRequest.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (ipAddress == null || ipAddress.ToLower() == "unknown")
                    ipAddress = currentRequest.ServerVariables["REMOTE_ADDR"];

                return ipAddress;
            }
            catch 
            {
                return "";
            }
        }
    }
}